package com.zhanghe.wzq.handler.request;

import com.zhanghe.wzq.User;
import com.zhanghe.wzq.command.request.JoinTableRequest;
import com.zhanghe.wzq.command.response.JoinTableResponse;
import com.zhanghe.wzq.data.Attributes;
import com.zhanghe.wzq.data.TableManager;
import com.zhanghe.wzq.data.UserChannelManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * JoinTableRequestHanlder
 *
 * @author Clevo
 * @date 2018/12/31
 */
public class JoinTableRequestHanlder extends SimpleChannelInboundHandler<JoinTableRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, JoinTableRequest joinTableRequest) throws Exception {
        User current = channelHandlerContext.channel().attr(Attributes.USER).get();
        if(current!=null){
            String tableId = joinTableRequest.getTableId();
            TableManager.INSTANCE.joinTable(current.getId(),tableId);
            JoinTableResponse response = new JoinTableResponse();
            response.setSuccess(true);
            response.setTableId(tableId);
            channelHandlerContext.channel().writeAndFlush(response);

            JoinTableResponse another = new JoinTableResponse();
            another.setSuccess(true);
            another.setTableId(tableId);
            another.setJoinUser(current.getId());
            String anotherUserId = TableManager.INSTANCE.getTableById(tableId).getAnotherUserId(current.getId());
            UserChannelManager.getInstance().getUserChannel(anotherUserId).writeAndFlush(another);
        }
    }
}
